<?php
	class ListingPlansController extends PaidListingsAppController
	{
		var $name = "ListingPlans";
		var $components = array('Auth');
		
		function beforeFilter()
		{
			$this->Auth->loginAction = "/users/login";
			parent::beforeFilter();
		}
		function index($listingId)
		{
			$ownerId = cri("Listing")->field("owner_id",array("id"=>$listingId));
			if(!$ownerId || $ownerId != $this->Session->read("Auth.User.id"))
			{
				$this->errorMsg("Invalid Listing");
				$this->redirect("/");
			}
			$ListingModel = cri("Listing");
			$ListingModel->recursive = -1;
			$listing = $ListingModel->findById($listingId);
			$listingPlans = $this->ListingPlan->find("all",array('conditions'=>array("listing_id"=>$listingId)));
			$this->helpers[] = "PaidListings.PlanDisplay";
			$this->helpers[] = "Time";
			$this->set("listing",$listing);
			$this->set("listingPlans",$listingPlans);
		}
		function initPlan()
		{
			if($this->data)
			{
				$ListingModel = cri("Listing");
				$planId = $this->data['ListingPlan']['plan_id'];
				$listingId = $this->data['ListingPlan']['listing_id'];
				$ownerId = $ListingModel->field("owner_id",array("id"=>$listingId));
				if($ownerId != $this->Session->read("Auth.User.id"))
				{
					$this->errorMsg("Invalid plan");
					$this->redirect("/");
				}
				$categoryId = $ListingModel->field('list_category_id',array("id"=>$listingId));
				if(cri("PaidListings.Plan")->isValidUpgradePlan($planId,$categoryId))
				{
					$Order = cri("PaidListings.Order");
					$listingPlanId = $this->ListingPlan->initPlanForListing($planId,$listingId,$this->Session->read("Auth.User.id"));
					$orderId = $Order->initOrder($listingPlanId);
					$this->redirect(array("action"=>'invoice',$orderId,'controller'=>"orders"));
				}else
					{
						$this->errorMsg(__("Please select a valid plan"));
						$this->redirect(array("action"=>"index",$listingId));
					}
			}
			$this->redirect("/");
		}
	}
?>